<?php

namespace liketp\socket;

use liketp\foundation\EventLoop;

class SocketWorker
{
    protected $server;
    protected $eventLoop;
    protected $handle;

    public function __construct(EventLoop $eventLoop, $ip, $port)
    {
        $server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        socket_bind($server, $ip, $port);
        socket_listen($server, 2);

        $this->server = $server;
        $this->eventLoop = $eventLoop;
        $this->eventLoop->add($this->server, 'READ', [$this, 'onConnect']);
    }

    public function setHandle($handle)
    {
        $this->handle = $handle;
    }

    public function onConnect($socket)
    {
        $client = socket_accept($socket);

        if ($this->handle && method_exists($this->handle, 'onConnect')) {
            $res = call_user_func_array([$this->handle, 'onConnect'], [$client]);
            if ($res === false) return;
        }
        $this->eventLoop->add($client, 'READ', [$this, 'onMessage']);
    }

    public function onMessage($client)
    {
        $msg = socket_read($client, 1024) ?: '';
        if ($this->handle && method_exists($this->handle, 'onMessage')) {
            call_user_func_array([$this->handle, 'onMessage'], [$client, $msg]);
        }
    }

    public function run()
    {
        $this->eventLoop->loop();
    }
}
